<?php
namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use think\Db;

class Auth extends BasicAdmin
{
    public $table = 'SystemAuth';

    /**
     * 数据列表展示
     * @return \think\response\View
     */
    public function index()
    {
        return view();
    }

    /**
     * 获取列表数据
     * @return \think\response\Json
     */
    public function getList(){
        $get_datas = $this->request->get();
        $where = [];

        $db = Db::name($this->table);

        if(isset($get_datas['title']) && $get_datas['title']) {
            $where[] = ['title', 'like', '%'.$get_datas['title'].'%'];
        }

        if(isset($get_datas['node']) && $get_datas['node']) {
            $where[] = ['node', 'like', '%'.$get_datas['node'].'%'];
        }

        $res  = DataService::getData($db, $get_datas['limit']??10, $where);

        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res['total'],
            'data'  => $res['data']
        ];
        return json($data);
    }

    /**
     * 添加信息
     * @return \think\response\View
     */
    public function create()
    {
        return view('');
    }

    /**
     * 保存信息
     * @return \think\response\Json
     */
    public function store()
    {
        $data = $this->request->post();
        $result = DataService::save(Db::name($this->table), $data, 'id', []);
        $data = [
            'code' => 200,
            'msg'   => '添加成功',
        ];
        return json($data);
    }

    /**
     * 权限授权
     * @param int $auth_id
     * @return \think\response\View
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function apply($auth_id)
    {
        $method = '_apply_' . strtolower($this->request->get('action', 'getnode'));
        if (method_exists($this, $method)) {
            $res =  $this->$method($auth_id);
            foreach ($res as $k=>&$v){
                $v['new_node'] = str_replace('/','_',$v['node']);
                foreach ($v['_sub_'] as $kk=>&$vv){
                    $vv['new_node'] = str_replace('/','_',$vv['node']);
                    foreach ($vv['_sub_'] as $kk2=>&$vv2){
                        $vv2['new_node'] = str_replace('/','_',$vv2['node']);
                    }
                }
            }
        }
        if($this->request->isPost()){
            $res = $this->_apply_save($auth_id);
            $this->success('节点授权更新成功！', 'auth/index');
        }

        $is_chose =  Db::name('SystemAuthNode')->where(['auth' => $auth_id])->column('node');

        $data['is_chose'] = $is_chose;
        $data['nodes'] = $res;
        $data['id'] = $auth_id;
        $data['role'] =  Db::name($this->table)->where(['id' => $auth_id])->find();

        $this->assign('title', '节点授权');

        return view('', $data);
    }

    /**
     * 读取授权节点
     * @param int $auth_id
     * @return mixed
     */
    protected function _apply_getnode($auth_id)
    {
        $nodes = NodeService::get();
        $checked = Db::name('SystemAuthNode')->where(['auth' => $auth_id])->column('node');
        foreach ($nodes as &$node) {
            $node['checked'] = in_array($node['node'], $checked);
        }
        return $all = $this->_apply_filter(ToolsService::arr2tree($nodes, 'node', 'pnode', '_sub_'));

        //$this->success('获取节点成功！', '', $all);
    }

    /**
     * 保存授权节点
     * @param int $auth_id
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    protected function _apply_save($auth_id)
    {
        list($data, $post) = [[], $this->request->post()];
        foreach (isset($post['nodes']) ? $post['nodes'] : [] as $node) {
            $data[] = ['auth' => $auth_id, 'node' => $node];
        }
        Db::name('SystemAuthNode')->where(['auth' => $auth_id])->delete();
        Db::name('SystemAuthNode')->insertAll($data);
    }

    /**
     * 节点数据拼装
     * @param array $nodes
     * @param int $level
     * @return mixed
     */
    protected function _apply_filter($nodes, $level = 1)
    {
        foreach ($nodes as $key => &$node) {
            if (!empty($node['_sub_']) && is_array($node['_sub_'])) {
                $node['_sub_'] = $this->_apply_filter($node['_sub_'], $level + 1);
            }
        }
        return $nodes;
    }

    /**
     * 修改信息页面
     * @param int $id  信息的主键id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {
        $res = Db::name($this->table)->where('id',$id)->find();
        $data = ['data'=>$res];
        return view('',$data);
    }

    /**
     * 保存修改信息
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function update()
    {
        $data = $this->request->post();
        $id = $data['id'];
        $res = Db::name($this->table)->where('id',$id)->update($data);
        if($res) {
            $data = [
                'code' => 200,
                'msg'   => '更新成功',
            ];
        } else {
            $data = [
                'code' => 0,
                'msg'   => '更新失败',
            ];
        }

        return json($data);
    }

    /**
     * 删除信息 ids 【批量删除】
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function destroy()
    {
        $ids = $this->request->post();
        if (empty($ids['ids'])){
            return json(['code'=>0,'msg'=>'请选择删除项']);
        }
        $res = Db::name($this->table)->whereIn('id', $ids['ids'])->delete();
        if($res) {
            Db::name('SystemAuthNode')->whereIn('auth', $ids['ids'])->delete();
            $data = [
                'code' => 200,
                'msg'   => '删除成功',
            ];
        } else {
            $data = [
                'code' => 0,
                'msg'   => '删除失败',
            ];
        }

        return json($data);
    }

    public function updateAct(){
        $data = $this->request->post();
        $res = Db::name($this->table)->where('id', $data['id'])->update([$data['act'] => $data['value']]);
        if($res) {
            $data = [
                'code' => 200,
                'msg'   => '更新成功',
            ];
        } else {
            $data = [
                'code' => 0,
                'msg'   => '更新失败',
            ];
        }
        return json($data);
    }

}
